<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API 测试页面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #3d8944 0%, #2d7a30 100%);
            color: #fff;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 14px;
            opacity: 0.9;
        }

        .api-url {
            background: rgba(255, 255, 255, 0.1);
            padding: 10px 15px;
            border-radius: 6px;
            margin-top: 15px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            word-break: break-all;
        }

        .content {
            padding: 30px;
        }

        .control-panel {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: #3d8944;
            color: #fff;
        }

        .btn-primary:hover {
            background: #2d7a30;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(61, 137, 68, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
            color: #fff;
        }

        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        .btn-danger {
            background: #dc3545;
            color: #fff;
        }

        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-2px);
        }

        .btn:active {
            transform: translateY(0);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .status {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
            animation: slideIn 0.3s;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .status.show {
            display: block;
        }

        .status-loading {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            color: #856404;
        }

        .status-success {
            background: #d4edda;
            border-left: 4px solid #28a745;
            color: #155724;
        }

        .status-error {
            background: #f8d7da;
            border-left: 4px solid #dc3545;
            color: #721c24;
        }

        .status-icon {
            display: inline-block;
            margin-right: 8px;
            font-size: 18px;
        }

        .result-container {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            position: relative;
        }

        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .result-header h3 {
            font-size: 18px;
            color: #333;
        }

        .result-stats {
            display: flex;
            gap: 20px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        .stat-item {
            background: #fff;
            padding: 10px 15px;
            border-radius: 6px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .stat-label {
            font-size: 12px;
            color: #6c757d;
            margin-bottom: 4px;
        }

        .stat-value {
            font-size: 20px;
            font-weight: bold;
            color: #3d8944;
        }

        .json-viewer {
            background: #282c34;
            color: #abb2bf;
            padding: 20px;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.6;
            overflow-x: auto;
            max-height: 600px;
            overflow-y: auto;
        }

        .json-viewer::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        .json-viewer::-webkit-scrollbar-track {
            background: #1e2127;
            border-radius: 4px;
        }

        .json-viewer::-webkit-scrollbar-thumb {
            background: #3d8944;
            border-radius: 4px;
        }

        .json-key {
            color: #e06c75;
        }

        .json-string {
            color: #98c379;
        }

        .json-number {
            color: #d19a66;
        }

        .json-boolean {
            color: #56b6c2;
        }

        .json-null {
            color: #c678dd;
        }

        .copy-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            padding: 8px 16px;
            background: #3d8944;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .result-container:hover .copy-btn {
            opacity: 1;
        }

        .copy-btn:hover {
            background: #2d7a30;
        }

        .spinner {
            display: inline-block;
            width: 14px;
            height: 14px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top-color: #fff;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        @media (max-width: 768px) {
            .header h1 {
                font-size: 22px;
            }

            .content {
                padding: 20px;
            }

            .control-panel {
                flex-direction: column;
            }

            .btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 API 测试工具</h1>
            <p>热门推荐服务列表接口测试</p>
            <div class="api-url">
                GET https://anfine.huasun-healthcare.com/api/hot_recommend/hotRecommend/list
            </div>
            <div class="api-url" id="tokenInfo" style="margin-top: 10px; font-size: 12px;">
                Token: 加载中...
            </div>
        </div>

        <div class="content">
            <div class="control-panel">
                <button class="btn btn-primary" onclick="fetchData()" id="fetchBtn">
                    <span id="btnIcon">▶</span>
                    <span id="btnText">发起请求</span>
                </button>
                <button class="btn btn-secondary" onclick="toggleFormat()">
                    <span>📋</span>
                    <span>切换格式</span>
                </button>
                <button class="btn btn-danger" onclick="clearResult()">
                    <span>🗑️</span>
                    <span>清空结果</span>
                </button>
            </div>

            <!-- 状态提示 -->
            <div id="statusBar" class="status"></div>

            <!-- 结果统计 -->
            <div id="statsContainer" style="display: none;">
                <div class="result-stats">
                    <div class="stat-item">
                        <div class="stat-label">响应时间</div>
                        <div class="stat-value" id="responseTime">-</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-label">数据条数</div>
                        <div class="stat-value" id="dataCount">-</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-label">状态码</div>
                        <div class="stat-value" id="statusCode">-</div>
                    </div>
                </div>
            </div>

            <!-- 结果展示 -->
            <div class="result-container" id="resultContainer" style="display: none;">
                <div class="result-header">
                    <h3>📦 响应数据</h3>
                    <button class="copy-btn" onclick="copyResult()">复制 JSON</button>
                </div>
                <pre id="result" class="json-viewer"></pre>
            </div>
        </div>
    </div>

    <script>
        const API_URL = 'https://anfine.huasun-healthcare.com/api/hot_recommend/hotRecommend/listByHospitalId?hospitalId=1';
        let lastResponse = null;
        let isFormatted = true;

        // 从 URL 获取参数
        function getUrlParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }

        // 获取 token
        const token = getUrlParam('token');

        /**
         * 将扁平数据转换为树形结构
         * @param {Array} list - 扁平数组数据
         * @param {String} pidField - 父ID字段名，默认 'pid'
         * @param {String} idField - ID字段名，默认 'id'
         * @param {String} childrenField - 子节点字段名，默认 'children'
         * @param {String} rootValue - 根节点的父ID值，默认 '0'
         * @returns {Array} 树形结构数据
         */
        function buildTree(list, pidField = 'pid', idField = 'id', childrenField = 'children', rootValue = '0') {
            if (!list || !Array.isArray(list) || list.length === 0) {
                return [];
            }

            // 创建一个映射表，key 为 id，value 为节点对象
            const map = {};
            const tree = [];

            // 深拷贝数据，避免修改原始数据
            const listCopy = JSON.parse(JSON.stringify(list));

            // 第一步：创建映射表
            listCopy.forEach(item => {
                map[item[idField]] = item;
                // 初始化 children 数组
                item[childrenField] = [];
            });

            // 第二步：构建树形结构
            listCopy.forEach(item => {
                const parent = map[item[pidField]];
                
                if (parent) {
                    // 如果找到父节点，将当前节点添加到父节点的 children 中
                    parent[childrenField].push(item);
                } else if (item[pidField] === rootValue || !item[pidField]) {
                    // 如果没有父节点，或者 pid 等于根节点值，则为根节点
                    tree.push(item);
                }
            });

            // 第三步：清理空的 children 数组
            function cleanEmptyChildren(nodes) {
                nodes.forEach(node => {
                    if (node[childrenField] && node[childrenField].length === 0) {
                        delete node[childrenField];
                    } else if (node[childrenField] && node[childrenField].length > 0) {
                        cleanEmptyChildren(node[childrenField]);
                    }
                });
            }

            cleanEmptyChildren(tree);

            return tree;
        }

        /**
         * 递归统计树形结构的节点数量
         */
        function countTreeNodes(tree, childrenField = 'children') {
            let count = 0;
            
            function traverse(nodes) {
                if (!nodes || !Array.isArray(nodes)) return;
                
                nodes.forEach(node => {
                    count++;
                    if (node[childrenField]) {
                        traverse(node[childrenField]);
                    }
                });
            }
            
            traverse(tree);
            return count;
        }

        // 显示状态消息
        function showStatus(type, message) {
            const statusBar = document.getElementById('statusBar');
            statusBar.className = `status status-${type} show`;
            
            const icons = {
                loading: '⏳',
                success: '✅',
                error: '❌'
            };
            
            statusBar.innerHTML = `<span class="status-icon">${icons[type]}</span>${message}`;
        }

        // 隐藏状态消息
        function hideStatus() {
            const statusBar = document.getElementById('statusBar');
            statusBar.classList.remove('show');
        }

        // 请求数据
        async function fetchData() {
            // 检查是否有 token
            if (!token) {
                showStatus('error', '缺少 token 参数！请在 URL 中添加 ?token=xxx');
                return;
            }

            const fetchBtn = document.getElementById('fetchBtn');
            const btnIcon = document.getElementById('btnIcon');
            const btnText = document.getElementById('btnText');
            
            // 禁用按钮
            fetchBtn.disabled = true;
            btnIcon.innerHTML = '<span class="spinner"></span>';
            btnText.textContent = '请求中...';
            
            showStatus('loading', '正在发送请求...');
            
            const startTime = Date.now();
            
            try {
                // 构建请求头，带上 token
                const headers = {
                    'Content-Type': 'application/json',
                    'X-Access-Token': token
                };

                const response = await fetch(API_URL, {
                    method: 'GET',
                    headers: headers,
                });
                
                const endTime = Date.now();
                const responseTime = endTime - startTime;
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                lastResponse = data;
                
                // 如果数据结构包含 result 数组，转换为树形结构
                if (data.result && Array.isArray(data.result)) {
                    const treeData = buildTree(data.result);
                    data.treeResult = treeData;
                    
                    console.log('=== 原始扁平数据 ===');
                    console.log(data.result);
                    console.log('=== 转换后的树形数据 ===');
                    console.log(treeData);
                    console.log('==================');
                }
                
                // 显示成功消息
                showStatus('success', `请求成功！耗时 ${responseTime}ms`);
                
                // 更新统计信息
                updateStats(responseTime, data, response.status);
                
                // 显示结果
                displayResult(data);
                
                // 在控制台打印
                console.log('=== API 响应数据 ===');
                console.log(data);
                console.log('==================');
                
                setTimeout(hideStatus, 3000);
                
            } catch (error) {
                console.error('请求失败:', error);
                showStatus('error', `请求失败: ${error.message}`);
                
                // 显示错误信息
                document.getElementById('resultContainer').style.display = 'block';
                document.getElementById('result').textContent = `错误: ${error.message}\n\n请检查:\n1. 网络连接是否正常\n2. API 地址是否正确\n3. 是否需要认证 token\n4. 跨域问题 (CORS)`;
            } finally {
                // 恢复按钮
                fetchBtn.disabled = false;
                btnIcon.textContent = '▶';
                btnText.textContent = '发起请求';
            }
        }

        // 更新统计信息
        function updateStats(responseTime, data, statusCode) {
            document.getElementById('statsContainer').style.display = 'block';
            document.getElementById('responseTime').textContent = `${responseTime}ms`;
            document.getElementById('statusCode').textContent = statusCode;
            
            // 计算数据条数
            let count = 0;
            let treeCount = 0;
            
            if (data && data.result) {
                if (Array.isArray(data.result)) {
                    count = data.result.length;
                } else if (data.result.records) {
                    count = data.result.records.length;
                } else if (data.result.total !== undefined) {
                    count = data.result.total;
                }
            }
            
            // 如果有树形数据，统计树形节点数
            if (data && data.treeResult) {
                treeCount = countTreeNodes(data.treeResult);
            }
            
            if (treeCount > 0) {
                document.getElementById('dataCount').textContent = `${count} (树形: ${treeCount} 节点)`;
            } else {
                document.getElementById('dataCount').textContent = count;
            }
        }

        // 显示结果
        function displayResult(data) {
            document.getElementById('resultContainer').style.display = 'block';
            
            if (isFormatted) {
                document.getElementById('result').innerHTML = syntaxHighlight(JSON.stringify(data, null, 2));
            } else {
                document.getElementById('result').textContent = JSON.stringify(data);
            }
        }

        // JSON 语法高亮
        function syntaxHighlight(json) {
            json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
            return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                let cls = 'json-number';
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = 'json-key';
                    } else {
                        cls = 'json-string';
                    }
                } else if (/true|false/.test(match)) {
                    cls = 'json-boolean';
                } else if (/null/.test(match)) {
                    cls = 'json-null';
                }
                return '<span class="' + cls + '">' + match + '</span>';
            });
        }

        // 切换格式
        function toggleFormat() {
            if (!lastResponse) {
                alert('请先发起请求获取数据');
                return;
            }
            
            isFormatted = !isFormatted;
            displayResult(lastResponse);
        }

        // 复制结果
        function copyResult() {
            if (!lastResponse) {
                alert('没有数据可复制');
                return;
            }
            
            const text = JSON.stringify(lastResponse, null, 2);
            
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(() => {
                    showStatus('success', '已复制到剪贴板！');
                    setTimeout(hideStatus, 2000);
                }).catch(err => {
                    console.error('复制失败:', err);
                    fallbackCopy(text);
                });
            } else {
                fallbackCopy(text);
            }
        }

        // 备用复制方法
        function fallbackCopy(text) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            document.body.appendChild(textArea);
            textArea.select();
            
            try {
                document.execCommand('copy');
                showStatus('success', '已复制到剪贴板！');
                setTimeout(hideStatus, 2000);
            } catch (err) {
                console.error('复制失败:', err);
                alert('复制失败，请手动复制');
            }
            
            document.body.removeChild(textArea);
        }

        // 清空结果
        function clearResult() {
            lastResponse = null;
            document.getElementById('resultContainer').style.display = 'none';
            document.getElementById('statsContainer').style.display = 'none';
            document.getElementById('result').textContent = '';
            hideStatus();
        }

        // 页面加载完成后的提示
        window.addEventListener('DOMContentLoaded', function() {
            console.log('%c🚀 API 测试页面已就绪', 'font-size: 20px; color: #3d8944; font-weight: bold;');
            console.log('%cAPI URL:', 'font-weight: bold;', API_URL);
            
            const tokenInfo = document.getElementById('tokenInfo');
            
            if (token) {
                console.log('%c✅ Token 已获取:', 'font-weight: bold; color: #28a745;', token.substring(0, 20) + '...');
                console.log('%c点击"发起请求"按钮开始测试', 'font-size: 14px; color: #666;');
                tokenInfo.innerHTML = `<span style="color: #a8ffa8;">✅ Token: ${token.substring(0, 30)}...</span>`;
                showStatus('success', `Token 已加载（${token.substring(0, 20)}...）`);
                setTimeout(hideStatus, 3000);
            } else {
                console.log('%c⚠️  未找到 Token', 'font-weight: bold; color: #dc3545;');
                console.log('%c请在 URL 中添加 token 参数，例如: test.html?token=your_token_here', 'color: #666;');
                tokenInfo.innerHTML = '<span style="color: #ffb3b3;">❌ 未找到 Token（请在 URL 中添加 ?token=xxx）</span>';
                showStatus('error', '未找到 Token！请在 URL 中添加 ?token=xxx');
            }
        });

        // 支持回车键发起请求
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Enter' && event.ctrlKey) {
                fetchData();
            }
        });
    </script>
</body>
</html>

